package org.ftc.web;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.ftc.domain.RoleAuth;
import org.ftc.domain.Users;
import org.ftc.form.UsersForm;
import org.ftc.security.User;
import org.ftc.service.FtcLogService;
import org.ftc.service.FtcLogService.Log;
import org.ftc.service.LoadUserDataTaskService;
import org.ftc.service.RoleAuthService;
import org.ftc.service.UsersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttributes;

@Controller
@SessionAttributes("SECURITY_USERS")
public class IndexController {
	@Autowired
	UsersService usersService;
	@Autowired
	RoleAuthService roleAuthService;
	@Autowired
	LoadUserDataTaskService loadUserService;
	@Autowired
	FtcLogService logService;

	@RequestMapping(value = "/index.htm")
	public String index(ModelMap model) {
		return "index";
	}
	
	@RequestMapping(value = "/dispatcher.htm")
	public String dispatcher(ModelMap model) {
		return "dispatcher";
	}

	@RequestMapping(value = "/home.htm")
	public String home(@RequestParam(value="type") String type, ModelMap model) {
		logService.before();
		if(StringUtils.equals(type, "2")){
			model.addAttribute("css", "css2"); 
			model.addAttribute("theme","metro-blue");
		}else{
			model.addAttribute("css", "css");
			model.addAttribute("theme","metro-green");
		}
		logService.save(Log.LOGING, "type:"+type, this.toString());
		return "home";
	}

	/**
	 * 因應登入資訊需核對公平會xml資料
	 * 登入控管排除spring security
	 * 改由以下程式控管
	 * @param userForm
	 * @param model
	 * @return
	 */
	@RequestMapping("/login.htm")
	public String login(UsersForm userForm, ModelMap model) {
		logService.before();
		boolean result = loadUserService.checkUser(userForm.getUserName(), userForm.getPassword());
		
		Users users = usersService.findByUserName(userForm.getUserName());
		if (result&&users!=null) {
			List<GrantedAuthority> authSet = new ArrayList<GrantedAuthority>();
			RoleAuth roleAuth = roleAuthService.get(users.getRole());
			if (roleAuth != null) {
				for (String auth : roleAuth.getAuths().split(",")) {
					authSet.add(new SimpleGrantedAuthority(auth));
				}
			}
			User user = new User(userForm.getUserName(), null, true, users.getRole(), authSet);
			Authentication authentication = new UsernamePasswordAuthenticationToken(user, null, authSet);
			SecurityContextHolder.getContext().setAuthentication(authentication);
			model.addAttribute("SECURITY_USERS", users);
			logService.save(Log.LOGING, userForm.getUserName(), this.toString());
			return "redirect:/dispatcher.htm";
		}  else {
			if(null!=users&&StringUtils.equals(userForm.getUserName(), users.getUserName())//
					&&StringUtils.equals(userForm.getPassword(), users.getPassword())){
				List<GrantedAuthority> authSet = new ArrayList<GrantedAuthority>();
				RoleAuth roleAuth = roleAuthService.get(users.getRole());
				if (roleAuth != null) {
					for (String auth : roleAuth.getAuths().split(",")) {
						authSet.add(new SimpleGrantedAuthority(auth));
					}
				}
				User user = new User(userForm.getUserName(), null, true, users.getRole(), authSet);
				Authentication authentication = new UsernamePasswordAuthenticationToken(user, null, authSet);
				SecurityContextHolder.getContext().setAuthentication(authentication);
				model.addAttribute("SECURITY_USERS", users);
				logService.save(Log.LOGING, userForm.getUserName(), this.toString());
				return "redirect:/dispatcher.htm";
			}else{
				return "redirect:/index.htm?login_error=t";
			}
		}
	}

	@RequestMapping("/logout.htm")
	public String logout(ModelMap model) {
		logService.before();
		Authentication userDetails = SecurityContextHolder.getContext().getAuthentication();
		logService.save(Log.LOGOUT, userDetails.getName(), this.toString());
		return "redirect:/j_spring_security_logout";
	}

	@RequestMapping("/accessDenied.htm")
	public String accessDenied(ModelMap model) {
		logService.before();
		Authentication userDetails = SecurityContextHolder.getContext().getAuthentication();
		System.out.println(userDetails.getName());
		System.out.println(userDetails.getDetails());
		logService.save(Log.LOGOUT, userDetails.getName(), this.toString());
		return "redirect:/index.htm?login_error=t";
	}

	// @RequestMapping(value = "/public/todayNotice.htm",
	// method=RequestMethod.POST)
	// public @ResponseBody List<Notice> todayNotice(NoticeForm noticeForm ) {
	// return noticeService.todayNotice(noticeForm.getPageType());
	// }

	// @RequestMapping(value = "/public/notice.htm" )
	// public @ResponseBody Notice notice(@RequestParam("id") String id ) {
	// return noticeService.get(id);
	// }

	// @RequestMapping(value = "/document.htm")
	// public String document( ModelMap model ) {
	// model.addAttribute("template", Template.values() );
	// model.addAttribute("centerNotice",
	// noticeService.todayNotice(Template.NOTICE01.name()) );
	// return "index";
	// }
}
